//todo: define rotate, translate and scale functions
function dot(V0, V1)
{
    return V0.x * V1.x + V0.y * V1.y;
}

function perp(v)
{
    return new Vector(v.y,-v.x);
}

function Point(x,y)
{
    this.x = x || 0.0;
    this.y = y || 0.0;
}

Point.prototype.constructor = new Vector;

function Vector(x,y)
{
    this.x = x || 0.0;
    this.y = y || 0.0;
    
    this.len = function() 
    {
        return Math.sqrt(this.x*this.x + this.y*this.y);
    }
    
    this.plus = function(v)
    {
        return new Vector(this.x + v.x, this.y + v.y);
    }
    
    this.minus = function(v)
    {
        return new Vector(this.x - v.x, this.y - v.y);
    }
    
    this.add = function(v)
    {
        this.x += v.x;
        this.y += v.y;
        return this;
    }
    
    this.sub = function(v)
    {
        this.x -= v.x;
        this.y -= v.y;
        return this;
    }
}

function Circle(c,r)
{
    this.c = c;
    this.r = r;
}

//defineste o raza din punctul P0 cu directia D0
function Ray(P0, D0)
{
    this.P = P0;
    this.D = D0;
    var len = Math.sqrt(D0.x*D0.x + D0.y*D0.y);
    this.cos = D0.x / len;
    this.sin = D0.y / len;
    
    //returneaza distanta pana la intersectia cu un segment dat de r
    this.intersectSegment = function(r)
    {
        alert(r.D);
        var D1 = r.D;
        var P1 = r.P;
        var dd = dot(perp(D1),this.D);
        var s,t;
        if (dd != 0)
        {
            s = dot(perp(D1),P1.minus(this.P))/dd;
            t = dot(perp(this.D),P1.minus(this.P))/dd;
            
            if (s >= 0 && 0 <= t && t <= 1)
            {
                ////intersection
                return s;
            }
        }
        return 0;
    }
    
    this.intersectCircle = function(s)
    {
       var EO = s.c.minus(this.P); 
       if (EO.len() < s.r)
       {
            return EO.len() - s.r;
       }
       else
       {
           var v = dot(EO,this.D);
           var disc = s.r*s.r - dot( EO, EO ) + v*v;
           if ( disc >= 0 )
           {
                return v - Math.sqrt( disc );
           }
       }
       return 0;
    }
}